<template>
	<view class="addcoupon">
		<button style="margin-top: 30rpx;" @click="coupons=!coupons">添加优惠券</button>
		<view class="" style="margin: 20rpx 0;font-size: 32rpx;">已有优惠券</view>
		<view v-for="(item, index) in array" :key="index">
			<view class="address-item">
				<view style="width: 73%;">
					<view class="topl">优惠券</view>
					<view class="name">{{item.name}}</view>
					<view class="address">有效期：{{item.endTime.substring(0,16)}}前</view>
				</view>
				<view style="float: right;">
					<view class="money" v-if="item.value>0"><text style="font-size: 28rpx;">￥</text>{{item.value}}</view>
					<view class="money" v-else><text style="font-size: 28rpx;"></text>{{item.value}}桶</view>
					<view style="color: #FF0000;font-size: 24rpx;margin-right: 20rpx;">满{{item.minAmount}}元可用</view>
				</view>
			</view>
		</view>
		<view class="couponsbox" v-if="coupons">
			<view class="inputbox">
				<img src="http://www.yuebi.online/images/de0e7da4-1782-4012-af90-e824b32bd13b.png" alt="" class="coupon1" @click="coupons=!coupons">
				<view class="">请输入优惠券名称：<input v-model="datalist.name" type="number" /></view>
				<view class="">请输入优惠券金额：<input v-model="datalist.value" type="number" /></view>
				<view class="">请选择优惠券类型：
					<picker @change="bindPickerChange2" :value="index" :range="addlist" range-key="text">
						<view class="input">{{type}}</view>
					</picker>
				</view>
				<view class="" v-if="datalist.type==2">最低使用订单额：<input v-model="datalist.minAmount" type="number" /></view>
				<view class="">优惠开始时间：
					<picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
					    <view class="input">{{ datalist.startTime }}</view>
					</picker>
				</view>
				<view class="">优惠结束时间：
					<picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange1">
					    <view class="input">{{ datalist.endTime }}</view>
					</picker>
				</view>
				<view class="">单个用户最多领取数量：<input v-model="datalist.eachClaimedCount" type="number" /></view>
				<view class="">上传优惠券图片：</view>
				<view class="cu-form-group" style="border-top: 0rpx solid #eee;">
					<view class="grid col-4 grid-square flex-sub">
						<view class="bg-img" v-for="(item,index) in imgList" :key="index" :data-url="imgList[index]">
							<image :src=item  mode="aspectFill" style="width: 50px;height: 50px;"></image>
							<view class="cu-tag bg-red"  @tap.stop="delImg" :data-index="index">
								<text class='cuIcon-close'></text>
							</view>
						</view>
						<view class="solids" @tap="chooseImage" v-if="imgList.length < count">
							<text class='cuIcon-cameraadd'>点击上传图片</text>
						</view>
					</view>
				</view>
				<button @click="addbtn()">添加</button>
			</view>
		</view>
	</view>
	
</template>
<script>
	import TabBar from '@/pages/common/components/TabBar.vue'
	import { saveSpecificUcoupon,couponsQueryAll,couponsSave } from '@/api/shop.js'
	export default {
		data () {
			return {
				array: [],
				addlist: [{
					type:1,
					text:'无限制'
				},{
					type:2,
					text:'满减'
				}],
				couponname:'',
				couponId:'',
				phone:'',
				coupons:false,
				datalist:{
					value:'',//优惠额
					type:'',//优惠券类型 1:无限制 2:满减
					minAmount:'',//最低使用订单额
					startTime:'',//优惠开始时间
					endTime:'',//优惠结束时间
					eachClaimedCount:'',//单个用户最多领取数量
					name:'',
					couponImg:''//优惠券图片
					
				},
				date: getDate({
				                format: true
				            }),
				startDate: getDate('start'),
				endDate: getDate('end'),
				type:'',
				//图片总允许上传数目
				count: 1,
				//存储服务器返回的文件名称
				imgList: [],
				//存储选择的本地图片文件路径列表
				tempImgList: [],
				//服务器图片资源获取接口
				baseUrl: 'http://www.yuebi.online/YBSsm2/exFunction/uploadImage.do',
			}
		},
		components: {
			TabBar
		},
		mounted () {
			this.getlist()
		},
		methods: {
			addbtn(){
				if(this.datalist.type==1){
					this.datalist.minAmount =0
				}
				if(this.imgList.length>0){
					this.datalist.couponImg = this.imgList[0]
					let data1 = this.datalist
					couponsSave(data1).then(res => {
						if(res.data.code==200){
							uni.showToast({
								title: '已成功添加',
								icon:"none"
							})
							this.coupons=!this.coupons
							this.getlist()
						}
						
					})
				}else{
					uni.showToast({
						title: '请上传首页优惠券图片',
						icon:"none"
					})
				}
				
			},
			bindPickerChange: function(e) {
				this.couponId = this.array[e.detail.value].id
				this.couponname = this.array[e.detail.value].name
			},
			getlist(){
				let data1 = {}
				couponsQueryAll(data1).then(res => {
					this.array = res.data.data
				})
			},
			bindDateChange: function(e) {
				const date = new Date(e.detail.value);//"2023-11-17"
				date.setHours(0, 0, 0);
				// 2. 使用Date对象的方法，获取年、月、日、小时、分钟和秒
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				const seconds = date.getSeconds().toString().padStart(2, '0');
				const formattedDateString = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			    this.datalist.startTime = formattedDateString;
			},
			bindDateChange1: function(e) {
				const date = new Date(e.detail.value);
				date.setHours(0, 0, 0);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				const seconds = date.getSeconds().toString().padStart(2, '0');
				const formattedDateString = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;	
			    // this.datalist.endTime = e.detail.value;
			    this.datalist.endTime = formattedDateString;
			},
			bindPickerChange2: function(e) {
				this.type = this.addlist[e.detail.value].text
				this.datalist.type = this.addlist[e.detail.value].type
			},
			/**
						 * 上传图片到服务器
						 */
						uploadImg(){
							uni.uploadFile({
								url: 'https://www.yuebi.online/exFunction/uploadImgFile', //真实的接口地址
								//每次保存最新的图片到服务器
								filePath: this.tempImgList[this.tempImgList.length-1],
								name: 'file',
								// header: {
								// 	'content-type': 'multipart/form-data',
								// 	'X-Access-Token': uni.getStorageSync('Access-Token')
								// },
								success: (uploadFileRes) => {
									let ress = JSON.parse(uploadFileRes.data)
									//将服务器返回的文件名进行存储，存储到记录对象中，使能从服务器获取图片资源
									this.imgList.push(ress.fileUrl);
								}
							});
						},
						/**
						 * 选择图片上传
						 */
						chooseImage() {
							uni.chooseImage({
								count: 1, //单词最多允许选中，默认9
								sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
								sourceType: ['album'], //从相册选择
								success: (res) => {
									// 获取到图片的本地文件路径列表，存储到临时列表tempImgList中
									if (this.tempImgList.length != 0) {
										this.tempImgList = this.tempImgList.concat(res.tempFilePaths)
									} else {
										this.tempImgList = res.tempFilePaths
									}
									
									let index = this.tempImgList[0].indexOf("blob:")
									let result = this.tempImgList[0].substr(index + 1,this.tempImgList[0].length)
									this.uploadImg()
								}
							});
						},
						/**
						 * 预览图片 urls所有的url地址，current选中的url地址
						 * @param {Object} e 
						 */
						viewImage(e) {
							uni.previewImage({
								urls: this.imgList,
								current: e.currentTarget.dataset.url
							});
						},
						/**
						 * 删除图片
						 * @param {Object} e
						 */
						delImg(e) {
							uni.showModal({
								title: '',
								content: '确定要删除第'+(e.currentTarget.dataset.index+1)+'张图片吗？',
								cancelText: '再看看',
								confirmText: '确定',
								success: res => {
									if (res.confirm) {
										this.imgList.splice(e.currentTarget.dataset.index, 1)
									}
								}
							})
						},
		},
		
	}
	function getDate(type) {
	    const date = new Date();
	 
	    let year = date.getFullYear();
	    let month = date.getMonth() + 1;
	    let day = date.getDate();
	 
	    if (type === 'start') {
	        year = year - 10;
	    } else if (type === 'end') {
	        year = year + 10;
	    }
	    month = month > 9 ? month : '0' + month;
	    day = day > 9 ? day : '0' + day;
	 
	    return `${year}-${month}-${day}`;
	}
</script>

<style scoped>
	.addcoupon{
		padding: 20rpx;
		padding-top: 0rpx;
		margin: 20rpx;
		font-size: 30rpx;
	}
	input,.input{
		border: 1rpx solid #1296db;
		height: 60rpx;
		line-height: 60rpx;
		margin: 15rpx 0;
		border-radius: 6rpx;
		font-size: 32rpx !important;
		padding-left: 20rpx;
		
	}
	.address-item {
		position: relative;
		margin: 26rpx 0;
		padding: 10rpx 5rpx;
		border: 1px solid #FDCFD3;
		background: #FEF1F2;
		padding: 20rpx 0;
		border-radius: 24rpx;
		overflow: hidden;
		display: flex;
		color: #545454;
	}
	.topl{
		position: absolute;
		top: -12rpx;
		left: -18rpx;
		font-size: 24rpx;
		border-radius: 0 0 28rpx 0;
		color: #fff;
		background: #FF0000;
		padding: 20rpx 20rpx 12rpx 36rpx;
	}
	.name {
		margin-top: 30rpx;
		font-size: 28rpx;
		margin-left: 30rpx;
		line-height: 48rpx;
	}
	.address {
		font-size: 24rpx;
		margin-left: 30rpx;
	}
	.money{
		color: #FF0000;
		font-size: 56rpx
	}
	.addres-edit {
		width: 80rpx;
		text-align: center;
		font-size: 30rpx;
		color: #fff;
		background: #FF0000;
		padding: 10rpx 12rpx;
		border-radius: 10rpx;
		margin-top: 30rpx;
		margin-left: 20rpx;
	}
	.btm{
		text-align: center;
		margin-top: 50rpx;
	}
	.couponsbox{
		position:fixed;
		z-index: 990 !important;
		height: 160%;
		color: #0a121e;
		background: rgba(0, 0, 0, 0.4); 
		left: 0%;
		right: 0%;
		margin-top: -500px;
		box-shadow: 2px -3px 100px -5px  #FFFFFF;
		text-shadow: #fff 0 3rpx 0;
	}
	.inputbox{
		position:fixed;
		z-index: 999 !important;
		top: 8rpx;
		background: #fff;
		border-radius: 10rpx;
		margin: 8% 10%;
		width: 68%;
		padding: 8% 6%;
	}
	.couponsbox button{
		margin-top: 50rpx;
		width: 180rpx;
		line-height: 84rpx;
		height: 84rpx;
		background: #1490e8;
		color: #fff;
		border: none;
	}
	.coupon1{
		width: 7%;
		height: 44rpx;
		position: absolute;
		top: 3%;
		left: 85%;
		z-index: 999 !important;
		border-radius: 14rpx;
	}
</style>